﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using KeepAccounts.Common.Config;

namespace KeepAccounts.Common
{
    public static class WeChatHelper
    {


        public static WeChatTokenModel getAccessToken(String code)
        {
            WebRequest request = WebRequest.Create(string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", WebConfig.WeCahtAppId, WebConfig.WeCahtAppSecert, code));
            request.Proxy = null;
            request.Credentials = CredentialCache.DefaultCredentials;

            //allows for validation of SSL certificates 

            ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate);
            // byte[] bs = Encoding.UTF8.GetBytes(string.Format(""));
            request.Method = "Get";
            //using (Stream reqStream = request.GetRequestStream())
            //{
            //    reqStream.Write(bs, 0, bs.Length);
            //}
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            if (responseFromServer.Contains("errcode"))
                return null;

            //LogService.LogHelper._Logger.Info("微信登录" + responseFromServer);
            return Newtonsoft.Json.JsonConvert.DeserializeObject<WeChatTokenModel>(responseFromServer);



        }

        public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        #region Test

        public static string getUserInfo(String openid, string accToken)
        {
            //  https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN
            //https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN
             
            WebRequest request = WebRequest.Create(string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", accToken, openid));
            request.Proxy = null;
            request.Credentials = CredentialCache.DefaultCredentials;

            //allows for validation of SSL certificates 

            ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate);
            // byte[] bs = Encoding.UTF8.GetBytes(string.Format(""));
            request.Method = "Get";
            //using (Stream reqStream = request.GetRequestStream())
            //{
            //    reqStream.Write(bs, 0, bs.Length);
            //}
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            if (responseFromServer.Contains("errcode"))
                return null;

            //LogService.LogHelper._Logger.Info("微信登录" + responseFromServer);
            return responseFromServer;



        }


        public static string getUserInfo(String openid)
        {
            //  https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN
            //https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN

            var token =  GetAccessToken();

            WebRequest request = WebRequest.Create(string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", token, openid));
            request.Proxy = null;
            request.Credentials = CredentialCache.DefaultCredentials;

            //allows for validation of SSL certificates 

            ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate);
            // byte[] bs = Encoding.UTF8.GetBytes(string.Format(""));
            request.Method = "Get";
            //using (Stream reqStream = request.GetRequestStream())
            //{
            //    reqStream.Write(bs, 0, bs.Length);
            //}
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            if (responseFromServer.Contains("errcode"))
                return null;

            //LogService.LogHelper._Logger.Info("微信登录" + responseFromServer);
            return responseFromServer;



        }

        //获取微信凭证access_token的接口
        public static string getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";

        #region 获取微信凭证
        public static string GetAccessToken()
        {
           // string accessToken = "";
            //获取配置信息Datatable
           
                string respText = ""; 
                //获取josn数据
                string url = string.Format(getAccessTokenUrl, WebConfig.WeCahtAppId, WebConfig.WeCahtAppSecert);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                using (Stream resStream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(resStream, Encoding.Default);
                    respText = reader.ReadToEnd();
                    resStream.Close();
                }
                //JavaScriptSerializer Jss = new JavaScriptSerializer();
                //Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(respText);
                //通过键access_token获取值
               // accessToken = respDic["access_token"].ToString();
           

            return respText;
        }
        #endregion 获取微信凭证


        #endregion

    }



    public class WeChatTokenModel
    {
        public string access_token { get; set; }
        public int expires_in { get; set; }
        public string refresh_token { get; set; }
        public string openid { get; set; }
        public string scope { get; set; }
        public string unionid { get; set; }
    }

}
